package com.example.ken.myapplication8;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import me.maxwin.view.XListView;

public class MainActivity extends AppCompatActivity {

    private Button fanhui,bianji,jiesuan;
    private TextView allmoney;
    private CheckBox quanxian;
    private XListView xListView;
    private int allmoneys = 0;
    public boolean flag_quanxuan = false;
    public  boolean flag_bianji = false;
    MyAdapter myAdapter;
    int ii = 1;
    ArrayList<MyData> lists;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String json = (String) msg.obj;
            Gson gson = new Gson();
            Bean bean = gson.fromJson(json, Bean.class);
            ArrayList<Bean.DataBean> data = (ArrayList<Bean.DataBean>) bean.getData();
            lists = new ArrayList<>();
            for (Bean.DataBean dd:
                 data) {
                MyData myData =new MyData();
                myData.setImage_one(dd.getPic());
                myData.setText_name(dd.getTitle());
                myData.setText_money(dd.getNum()+"");
                myData.setText_num(0);
                myData.setFlag(false);

                lists.add(myData);
            }
            myAdapter = new MyAdapter(lists);
            xListView.setAdapter(myAdapter);
            View header = LayoutInflater.from(MainActivity.this).inflate(R.layout.header,null);
            View footer = LayoutInflater.from(MainActivity.this).inflate(R.layout.footer,null);
            xListView.addHeaderView(header);
            xListView.addFooterView(footer);
            fanhui = header.findViewById(R.id.btn_fanhui);
            bianji = header.findViewById(R.id.bianji);
            jiesuan = footer.findViewById(R.id.jisuan);
            allmoney = footer.findViewById(R.id.text_allmoney);
            quanxian = footer.findViewById(R.id.check_quanxuan);

            jiesuan.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    int allmoneys=0;
                    for (MyData d:
                         lists) {
                        if(d.isFlag()==true) {
                            int danjia = Integer.parseInt(d.getText_money());
                            int num = d.getText_num();
                            allmoneys += (danjia * num);
                        }
                    }
                    allmoney.setText(allmoneys + "");
//                    myAdapter.notifyDataSetChanged();
                }
            });

            quanxian.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if(isChecked){
                        quanxian.setChecked(true);
                        flag_quanxuan = true;
                        myAdapter.notifyDataSetChanged();
                    }else{
                        quanxian.setChecked(false);
                        flag_quanxuan = false;
                        myAdapter.notifyDataSetChanged();
                    }
                }
            });

            bianji.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(flag_bianji){
                        flag_bianji = false;
                        myAdapter.notifyDataSetChanged();
                    }else{
                        flag_bianji = true;
                        myAdapter.notifyDataSetChanged();
                    }
                }
            });

            fanhui.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });

        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        xListView = findViewById(R.id.xlv);

        xListView.setPullLoadEnable(true);
        xListView.setPullRefreshEnable(true);

        new MyThread("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page=1").start();

        xListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                ii=1;
                new Thread("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page="+ii).start();
//                xListView.stopRefresh();
//                xListView.stopLoadMore();
                myAdapter.notifyDataSetChanged();
            }

            @Override
            public void onLoadMore() {
                ii++;
                if(ii>30){
                    ii=30;
                }
                new Thread("http://www.qubaobei.com/ios/cf/dish_list.php?stage_id=1&limit=10&page="+ii).start();

//                xListView.stopRefresh();
//                xListView.stopLoadMore();
                myAdapter.notifyDataSetChanged();

            }
        });



//        Toast.makeText(this, allmoneys+"", Toast.LENGTH_SHORT).show();



    }
    class MyThread extends Thread{
        String str;
        public MyThread(String s){
            this.str=s;
        }
        @Override
        public void run() {
            super.run();
            try {
                URL url = new URL(str);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setReadTimeout(3000);
                connection.setConnectTimeout(3000);
                if(connection.getResponseCode()==200){
                    InputStream inputStream = connection.getInputStream();
                    byte[] bys = new byte[1024];
                    StringBuffer str = new StringBuffer();
                    int len = 0;
                    while((len=inputStream.read(bys))!=-1){

                        str.append(new String(bys,0,len));

                    }
                    Message message = Message.obtain();
                    message.obj = str.toString();
                    handler.sendMessage(message);
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    class MyAdapter extends BaseAdapter{


        ArrayList<MyData> list;
        public MyAdapter( ArrayList<MyData> data){
            this.list=data;
        }
        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder viewHolder;
             int num = 0;
            if(convertView==null){
                convertView = LayoutInflater.from(MainActivity.this).inflate(R.layout.tuwenwen_layout,null);
                viewHolder = new ViewHolder();
                viewHolder.image_one = convertView.findViewById(R.id.image_one);
                viewHolder.text_name = convertView.findViewById(R.id.text_name);
                viewHolder.text_money = convertView.findViewById(R.id.text_money);
                viewHolder.text_num = convertView.findViewById(R.id.text_num);
                viewHolder.check_one = convertView.findViewById(R.id.check_one);
                viewHolder.btn_jia = convertView.findViewById(R.id.btn_jia);
                viewHolder.btn_jian = convertView.findViewById(R.id.btn_jian);
                viewHolder.shanchu = convertView.findViewById(R.id.btn_shanchu);

                convertView.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) convertView.getTag();
            }

            final MyData dataBean = list.get(position);

            viewHolder.btn_jia.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(MainActivity.this, "添加数量", Toast.LENGTH_SHORT).show();
                    int aa = dataBean.getText_num();
                    if(++aa==99){
                        Toast.makeText(MainActivity.this, "已达到最大数量", Toast.LENGTH_SHORT).show();
                    }else {
                        dataBean.setText_num(aa);
                        myAdapter.notifyDataSetChanged();
                    }
                }
            });

            viewHolder.btn_jian.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
//                    Toast.makeText(MainActivity.this, "减少数量", Toast.LENGTH_SHORT).show();
                    int aa = dataBean.getText_num();
                    if(--aa<0){
                        Toast.makeText(MainActivity.this, "已达到最低数量", Toast.LENGTH_SHORT).show();
                    }else {
                        dataBean.setText_num(aa);
                        myAdapter.notifyDataSetChanged();
                    }
                }
            });

            viewHolder.shanchu.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.remove(position);
                    myAdapter.notifyDataSetChanged();
                }
            });
            viewHolder.check_one.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    dataBean.setFlag(isChecked);
                }
            });

            viewHolder.text_name.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Toast.makeText(MainActivity.this, dataBean.getText_name(), Toast.LENGTH_SHORT).show();
                }
            });



            viewHolder.text_name.setText(dataBean.getText_name());
            viewHolder.text_money.setText(dataBean.getText_money());
            Picasso.with(MainActivity.this).load(dataBean.getImage_one()).into(viewHolder.image_one);

            if(flag_bianji){
                viewHolder.shanchu.setVisibility(View.VISIBLE);
            }else{
                viewHolder.shanchu.setVisibility(View.GONE);
            }

            if(flag_quanxuan){
                viewHolder.check_one.setChecked(true);
                dataBean.setFlag(true);
                //myAdapter.notifyDataSetChanged();
            }else{
                viewHolder.check_one.setChecked(false);
                dataBean.setFlag(false);
                //myAdapter.notifyDataSetChanged();
            }

            viewHolder.text_num.setText(dataBean.getText_num()+"");

//            int money = Integer.parseInt(viewHolder.text_money.getText().toString());
//            int nums =  Integer.parseInt(viewHolder.text_num.getText().toString());
//            int countmoney = money*nums;
//            allmoneys+=countmoney;

            return convertView;
        }
    }
    class ViewHolder {
        ImageView image_one;
        CheckBox check_one;
        TextView text_name;
        TextView text_money;
        Button btn_jia;
        Button btn_jian;
        TextView text_num;
        Button shanchu;
    }
}
